<?php 		
	
	include_once "post_model.php";
	include_once "user_model.php";	
	include_once "achievement_model.php";
	
	class Comment_Model {
		
		//mengembalikan ID comment yang baru saja di-insert jika insert berhasil, mengembalikan false jika terjadi error
		public function insertComment($username_id, $post_id, $content) {
		
			$post_model = new Post_Model();
			$user_model = new User_Model();
		
			$ret1 = mysql_query("INSERT INTO comment (username_id, post_id, datetime, content)
							VALUES ('$username_id', '$post_id', NOW(), '$content')") or die(mysql_error());
			$new_id = mysql_insert_id();			
			
			$ret2 = $post_model->incPostCommentCount($post_id);
			$ret3 = $user_model->incUserCommentCount($username_id);
			
			//otomatis dapet achievement komen pertama
			$achievement_model = new Achievement_Model();
			$achievement_model->addAchievementToUser($username_id, Achievement_Model::COMMENT_ONCE);
			
			$user_model = new User_Model();
			
			//jika diatas 10 kali			
			$user_res = $user_model->getUserInfo($username_id);			
			$user_row = mysql_fetch_array($user_res);
			if($user_row["comment_count"] >= 20) {
				$achievement_model->addAchievementToUser($username_id, Achievement_Model::COMMENT_20);
			}			
			
			if($ret1 && $ret2 && $ret3) {
				return $new_id;
			}else return false;			
		}
					
		public function delComment($comment_id) {
			
			$comment_res = $this->getComment($comment_id);
			$row = mysql_fetch_array($comment_res);
			
			$post_model = new Post_Model();
			$user_model = new User_Model();
			
			$ret1 = $post_model->decPostCommentCount($row['post_id']);
			$ret2 = $user_model->decUserCommentCount($row['username_id']);
			
			$ret3 = mysql_query("DELETE FROM comment
								WHERE ID=$comment_id");			
			
			return $ret1 && $ret2 && $ret3;							
		}
					
		public function	getAllComment($post_id) {
			$res = mysql_query("SELECT comment.ID AS comment_id,username_id, user.username AS username, comment.datetime AS datetime, comment.content AS content, avatar 
							FROM comment 
							INNER JOIN user 
							ON user.ID= comment.username_id 
							WHERE comment.post_id=$post_id 
							ORDER BY comment.datetime DESC") or die(mysql_error());
			return $res;
		}
		
		public function getComment($comment_id) {
			$res =  mysql_query("SELECT comment.ID AS comment_ID, username_id, user.username AS username, comment.datetime AS datetime, comment.content AS content, avatar, post_id 
							FROM comment 
							INNER JOIN user 
							ON user.ID= comment.username_id 
							WHERE comment.ID=$comment_id 
							LIMIT 1") or die(mysql_error());
			
			return $res;
		}
	}
?>